public class Solution160 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode p = headA, q = headB;
        while (p.next != null && q.next != null) {
            p = p.next;
            q = q.next;
        }
        int count = 0;
        if (p.next == null) {
            ListNode t = q;
            q = p;
            p = t;
            t = headA;
            headA = headB;
            headB = t;
        }
        while (p.next != null) {
            count++;
            p = p.next;
        }
        if (p != q) {
            return null;
        }
        p = headA;
        q = headB;
        while (count > 0) {
            p = p.next;
            count--;
        }
        while (q != null && p != q) {
            p = p.next;
            q = q.next;
        }
        return p;
    }
}
